// 更新管理器类
class UpdateManager {
  constructor() {
    this.status = 'idle';
    this.updateInfo = null;
    this.progressCallback = null;
    this.statusCallback = null;
    
    // 绑定更新状态监听
    this.bindUpdateListener();
  }

  // 绑定更新状态监听器
  bindUpdateListener() {
    if (window.api && window.api.onUpdateStatus) {
      window.api.onUpdateStatus((data) => {
        this.handleUpdateStatus(data);
      });
    }
  }

  // 处理更新状态变化
  handleUpdateStatus(data) {
    this.status = data.status;
    
    switch (data.status) {
      case 'checking':
        this.showUpdateMessage('正在检查更新...', 'info');
        break;
        
      case 'available':
        this.updateInfo = data.data;
        this.showUpdateAvailable(data.data);
        break;
        
      case 'not-available':
        this.showUpdateMessage('当前已是最新版本', 'success');
        break;
        
      case 'downloading':
        this.showDownloadProgress(data.data);
        break;
        
      case 'downloaded':
        this.updateInfo = data.data;
        this.showUpdateDownloaded();
        break;
        
      case 'error':
        this.showUpdateMessage(`更新错误: ${data.data.message}`, 'error');
        break;
    }

    // 调用状态回调
    if (this.statusCallback) {
      this.statusCallback(this.status, data.data);
    }
  }

  // 检查更新
  async checkForUpdates() {
    if (!window.api) {
      console.error('API not available');
      return;
    }

    try {
      const result = await window.api.checkForUpdates();
      if (!result.success) {
        this.showUpdateMessage(`检查更新失败: ${result.error}`, 'error');
      }
    } catch (error) {
      this.showUpdateMessage(`检查更新失败: ${error.message}`, 'error');
    }
  }

  // 下载更新
  async downloadUpdate() {
    if (!window.api) {
      console.error('API not available');
      return;
    }

    try {
      const result = await window.api.downloadUpdate();
      if (!result.success) {
        this.showUpdateMessage(`下载更新失败: ${result.error}`, 'error');
      }
    } catch (error) {
      this.showUpdateMessage(`下载更新失败: ${error.message}`, 'error');
    }
  }

  // 安装更新
  async installUpdate() {
    if (!window.api) {
      console.error('API not available');
      return;
    }

    try {
      const result = await window.api.installUpdate();
      if (!result.success) {
        this.showUpdateMessage(`安装更新失败: ${result.error}`, 'error');
      }
    } catch (error) {
      this.showUpdateMessage(`安装更新失败: ${error.message}`, 'error');
    }
  }

  // 获取更新状态
  async getUpdateStatus() {
    if (!window.api) {
      console.error('API not available');
      return null;
    }

    try {
      const result = await window.api.getUpdateStatus();
      if (result.success) {
        return result.data;
      } else {
        console.error('获取更新状态失败:', result.error);
        return null;
      }
    } catch (error) {
      console.error('获取更新状态失败:', error.message);
      return null;
    }
  }

  // 显示更新可用对话框
  showUpdateAvailable(updateInfo) {
    const modal = this.createModal('update-available', `
      <div class="update-modal-header">
        <h3>🎉 发现新版本</h3>
      </div>
      <div class="update-modal-body">
        <p><strong>新版本:</strong> v${updateInfo.version}</p>
        <p><strong>发布时间:</strong> ${new Date(updateInfo.releaseDate).toLocaleDateString()}</p>
        ${updateInfo.releaseNotes ? `
          <div class="update-notes">
            <h4>更新内容:</h4>
            <div class="release-notes">${updateInfo.releaseNotes}</div>
          </div>
        ` : ''}
      </div>
      <div class="update-modal-footer">
        <button class="btn btn-primary" onclick="updateManager.downloadUpdate()">立即下载</button>
        <button class="btn btn-secondary" onclick="updateManager.closeModal('update-available')">稍后提醒</button>
      </div>
    `);
  }

  // 显示下载进度
  showDownloadProgress(progressInfo) {
    const existingModal = document.getElementById('update-progress');
    const progressHtml = `
      <div class="update-modal-header">
        <h3>📥 正在下载更新</h3>
      </div>
      <div class="update-modal-body">
        <div class="progress-container">
          <div class="progress-bar">
            <div class="progress-fill" style="width: ${progressInfo.percent}%"></div>
          </div>
          <div class="progress-text">
            ${Math.round(progressInfo.percent)}% 
            (${this.formatBytes(progressInfo.transferred)} / ${this.formatBytes(progressInfo.total)})
          </div>
          <div class="progress-speed">
            下载速度: ${this.formatBytes(progressInfo.bytesPerSecond)}/s
          </div>
        </div>
      </div>
    `;

    if (existingModal) {
      existingModal.innerHTML = progressHtml;
    } else {
      this.createModal('update-progress', progressHtml);
    }
  }

  // 显示更新下载完成
  showUpdateDownloaded() {
    this.closeModal('update-progress');
    
    const modal = this.createModal('update-downloaded', `
      <div class="update-modal-header">
        <h3>✅ 更新已准备就绪</h3>
      </div>
      <div class="update-modal-body">
        <p>新版本已下载完成，重启应用以安装更新。</p>
      </div>
      <div class="update-modal-footer">
        <button class="btn btn-primary" onclick="updateManager.installUpdate()">立即重启</button>
        <button class="btn btn-secondary" onclick="updateManager.closeModal('update-downloaded')">稍后重启</button>
      </div>
    `);
  }

  // 显示更新消息
  showUpdateMessage(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `update-toast update-toast-${type}`;
    toast.innerHTML = `
      <div class="toast-content">
        <span class="toast-icon">${this.getToastIcon(type)}</span>
        <span class="toast-message">${message}</span>
      </div>
      <button class="toast-close" onclick="this.parentElement.remove()">×</button>
    `;

    document.body.appendChild(toast);

    // 自动移除
    setTimeout(() => {
      if (toast.parentElement) {
        toast.remove();
      }
    }, 5000);
  }

  // 创建模态框
  createModal(id, content) {
    // 移除现有的模态框
    this.closeModal(id);

    const modal = document.createElement('div');
    modal.id = id;
    modal.className = 'update-modal-overlay';
    modal.innerHTML = `
      <div class="update-modal">
        ${content}
      </div>
    `;

    document.body.appendChild(modal);
    return modal;
  }

  // 关闭模态框
  closeModal(id) {
    const modal = document.getElementById(id);
    if (modal) {
      modal.remove();
    }
  }

  // 获取Toast图标
  getToastIcon(type) {
    const icons = {
      info: 'ℹ️',
      success: '✅',
      error: '❌',
      warning: '⚠️'
    };
    return icons[type] || icons.info;
  }

  // 格式化字节数
  formatBytes(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  // 设置进度回调
  setProgressCallback(callback) {
    this.progressCallback = callback;
  }

  // 设置状态回调
  setStatusCallback(callback) {
    this.statusCallback = callback;
  }
}

// 创建全局更新管理器实例
window.updateManager = new UpdateManager();